package com.ayu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ayu.common.utils.R;
import com.ayu.gulimall.seckill.feign.ProductServiceFeign;
import com.ayu.gulimall.seckill.feign.SkuServiceFeign;
import com.ayu.gulimall.seckill.service.SeckillService;
import com.ayu.gulimall.seckill.to.SeckillSkuRedisTO;
import com.ayu.gulimall.seckill.to.SkuInfoVO;
import com.ayu.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.ayu.gulimall.seckill.vo.SeckillSkuVO;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import static org.checkerframework.checker.units.UnitsTools.s;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    SkuServiceFeign skuServiceFeign;

    @Autowired
    ProductServiceFeign productServiceFeign;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redissonClient;

    private final String SESSION_CACHE_PREFIX="seckill:sessions:";
    private final String SKU_CACHE_PREFIX ="seckill:skus";
    private final String SKU_STOCK_SEMAPHORE="seckill:stock:";//+uuid

    @Override
    public void getLast3DaySkus() {
        R r = skuServiceFeign.listLast3();


        String data = JSONObject.toJSONString(r.get("data"));
        List<SeckillSessionWithSkus> skusList = JSONObject.parseObject(data, new TypeReference<List<SeckillSessionWithSkus>>() {
        });
    //            1、缓存活动信息,格式：key：seckill：sessions+开始时间_结束时间
    //            value： 所有商品的Id
        this.saveSessions(skusList);
    //            2、缓存所有的商品信息
        this.saveSkus(skusList);
        System.out.println("进来了么。。。。。");

    }

    @Override
    public List<SeckillSkuRedisTO> getCurrentSeckillSkus() {
        //从redis里面得到
        Long now =new Date().getTime();
        Set<String> keys = stringRedisTemplate.keys(SESSION_CACHE_PREFIX + "*");
//        seckill:sessions:1613653200000_1613656800000
        System.out.println("keys = " + keys);
        List<String> list2=new ArrayList<>();
        for (String key:keys) {
            String replace = key.replace(SESSION_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            Long start =Long.parseLong(s[0]);
            Long end =Long.parseLong(s[1]);
            if(now>=start&&now<=end){
                //获取这个场次的商品信息
                List<String> range = stringRedisTemplate.opsForList().range(key,-100,100);
//                System.out.println("range = " + range);

                BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKU_CACHE_PREFIX);
//                List<String> list = hashOps.multiGet(range);

                range.stream().forEach(item->{
                    System.out.println("item = " + item);
                    String replace1 = item.replace("[", "").replace("]", "");
                    String s1 = hashOps.get(replace1);
                    System.out.println("s1 = " + s1);
                    list2.add(s1);
                });
            }
        }
        System.out.println("list2 = " + list2);
        //这个list应该就是商品信息了
        if(list2!=null){
            List<SeckillSkuRedisTO> collect = list2.stream().map(item -> {
                SeckillSkuRedisTO redisTO = JSONObject.parseObject(item, SeckillSkuRedisTO.class);
                return redisTO;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    public void saveSessions(List<SeckillSessionWithSkus> skusList){
            skusList.stream().forEach(session->{
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                //value:sessionId_skuId;
                List<String> collect = session.getSkuRelations().stream()
                        .map(item -> item.getPromotionSessionId().toString()+"_"+item.getSkuId().toString())
                        .collect(Collectors.toList());
                String key = SESSION_CACHE_PREFIX+startTime+"_"+endTime;
                System.out.println("key = " + key);
                Boolean hasKey = stringRedisTemplate.hasKey(key);
                if(!hasKey){
                    stringRedisTemplate.opsForList().leftPush(key, collect.toString());
                }


            });
    }
    public void saveSkus(List<SeckillSessionWithSkus> skusList){
        skusList.stream().forEach(session->{
            //给redis绑定hash操作
            BoundHashOperations ops = stringRedisTemplate.boundHashOps(SKU_CACHE_PREFIX);
            session.getSkuRelations().stream().forEach(skuVO->{
                if(!ops.hasKey(skuVO.getPromotionSessionId()+"_"+skuVO.getSkuId().toString())){
                    //缓存商品
                    SeckillSkuRedisTO redisTO =new SeckillSkuRedisTO();
    //                String s = JSONObject.toJSONString(skuVO);
    //              1、缓存商品的秒杀信息
                    BeanUtils.copyProperties(skuVO,redisTO);
    //              2、缓存商品的基本信息
                    R r = productServiceFeign.info(skuVO.getSkuId());
                    String skuDetailInfo = JSONObject.toJSONString(r.get("skuInfo"));
                    SkuInfoVO skuInfoVO = JSONObject.parseObject(skuDetailInfo, new TypeReference<SkuInfoVO>(){});
                    redisTO.setSkuInfoVO(skuInfoVO);
    //              3、缓存商品的随机码
                    String token =UUID.randomUUID().toString().replace("-","");
                    redisTO.setRandomCode(token);

    //              4、设置商品的开始和结束时间
                    redisTO.setStartTime(session.getStartTime().getTime());
                    redisTO.setEndTime(session.getEndTime().getTime());

    //              5、设置秒杀商品的分布式信号量****
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    int seckillCount = Integer.parseInt(skuVO.getSeckillCount().toBigInteger().toString());
                    System.out.println("商品库存是："+seckillCount);
                    semaphore.trySetPermits(seckillCount);


                    String s = JSONObject.toJSONString(redisTO);
                    ops.put(skuVO.getPromotionSessionId()+"_"+skuVO.getSkuId().toString(),s);
                }
            });
        });

    }
}
